package com.java.example.ui.viewmodel

import android.app.Application
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.AndroidViewModel
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.java.example.R
import com.java.example.databinding.FragmentProjectManagerBinding
import com.java.example.ui.adapter.FragmentIndexAdapter
import com.java.example.ui.fragment.DemoListFragment
import com.java.example.ui.fragment.ProjectListFragment

class ProjectManagerViewModel(application: Application) : AndroidViewModel(application) {
    lateinit var binding: FragmentProjectManagerBinding
    private var currentItem = 0

    fun init(requireContext: FragmentActivity) {
        val fragmentAdapter: FragmentIndexAdapter by lazy {
            val fragments: ArrayList<Fragment> = arrayListOf()
            fragments.add(ProjectListFragment())
            fragments.add(DemoListFragment())
            FragmentIndexAdapter(requireContext, fragments)
        }
        binding.viewpager.apply {
            setAdapter(fragmentAdapter)
            setUserInputEnabled(false)
            setOffscreenPageLimit(1)
            registerOnPageChangeCallback(MyPageChangeCallback())
            currentItem = 0
        }
    }

    inner class MyPageChangeCallback : OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            setCurrentPage(position)
        }
    }

    fun setCurrentPage(position: Int) {
        currentItem = position
        when (position) {
            0 -> {
                binding.tvProject.setTextColor(binding.tvProject.context.resources.getColor(R.color.mainColor))
                binding.tvProject.background = (binding.tvProject.context.resources.getDrawable(R.drawable.bg_ef_r30))
                binding.tvDemo.setTextColor(binding.tvProject.context.resources.getColor(R.color.white))
                binding.tvDemo.background = null

            }
            1 -> {
                binding.tvProject.setTextColor(binding.tvProject.context.resources.getColor(R.color.white))
                binding.tvProject.background = null
                binding.tvDemo.setTextColor(binding.tvProject.context.resources.getColor(R.color.mainColor))
                binding.tvDemo.background = (binding.tvProject.context.resources.getDrawable(R.drawable.bg_ef_r30))
            }
        }


    }

    fun changeTab(context: Context, index: Int) {
        binding.viewpager.setCurrentItem(index, false)
    }
}